package com.easytouch.core;

import android.os.SystemClock;
import android.support.annotation.NonNull;

import com.easytouch.core.utils.GoodsDataBase;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SimTools;
import com.easytouch.core.utils.SystemTools;
import com.easytouch.core.utils.Tools;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * 后台监控通信类
 * Created by gulin on 2017/2/14.
 */

public class MonitorThread extends Thread {

    private static MonitorThread mMonitorThread;

    private static final boolean isEnable = true;

    private Log logger = new Log("MonitorThread.txt");

    private boolean run = true;

    private String mStrSign = null; //保存签到数据

    // 76指令发送到后台的间隔时间
    private static final int DRIVER_TIME_76_NORMAL = 30000;
    private static final int DRIVER_TIME_76_FAST = 10000;
    private int mCurrentTime76 = DRIVER_TIME_76_NORMAL;
    private long mTime52 = 0;
    private long mTime61 = 0;
    private String mData61 = "-1";
    private long mTime62 = 0;
    private HashMap<Integer, String> mDataMap62 = new HashMap<Integer, String>();
    private long mTime63 = 0;
    private HashMap<Integer, String> mDataMap63 = new HashMap<Integer, String>();
    private long mTime81 = 0;
    private String mData81 = "-1";
    private long mTime83 = 0;
    private String mData83 = "-1";

    //定位的经纬度
    public static double mdLongitude = 0.0; //经度
    public static double mdLatitude = 0.0; //纬度
    private static int miLocationType = 0; //定位类型
    private long mlLastSend53 = 0; //最后一次发送53指令的时间
    //private static LocationClient mLocationClient;
    private static boolean isGPSEnable = false;

    private static final int RETRY_COUNT = 3;
    private int mRetryCount = 0;

    private MonitorThread()
    {}

    void stopThread()
    {
        run = false;
    }

    public static MonitorThread getInstance()
    {
        if(mMonitorThread == null)
        {
            mMonitorThread = new MonitorThread();

//            mLocationClient = new LocationClient(AppApplication.context);
//            mLocationClient.registerLocationListener(new MyLocationListener());
//            LocationClientOption option = new LocationClientOption();
//            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
//            option.setCoorType("gcj02");//返回的定位结果是百度经纬度，默认值gcj02
//            option.setScanSpan(600000);//设置发起定位请求的间隔时间为10分钟
//            mLocationClient.setLocOption(option);
//            mLocationClient.start();
        }
        return mMonitorThread;
    }

    private void insertDataToDB(String type, String message, String remark)
    {
        int retry = 3;
        for(int i = 1;i <= retry;i++)
        {
            if(GoodsDataBase.getInstance().insertMessage(type, message, remark))
            {
                return;
            }
            else
            {
                logger.e("insert db error, retry:" + i + " message:" + message);
            }
        }
    }

    /**
     * 获得请求报文头 35位不含2位控制码
     *
     * @return 报文头
     */
    @NonNull
    private String getMsgHeader()
    {
        StringBuffer str = new StringBuffer();
        String currentTime = Tools.getCurrentTime();
        str.append(currentTime).append(Configure.getMacNo()).append(Configure.MONITOR_VERSION).append("000001R");
        return str.toString();
    }

    /**
     * 51签到
     * @param pMacType 机器类型 2位
     * @param pDrinkNum 饮料机数量 1位
     * @param pFoodsNum 食品机数量 1位
     * @param pNoodleNum 商品柜数量 1位
     * @param pDrinkColumnNum 饮料机货道数 2位
     * @param pFoodsColumnNum 食品机货道数 2位
     * @param pNoodleColumnNum 商品柜货道数 2位
     */
    synchronized void addMessage51(final String pMacType, final String pDrinkNum, final String pFoodsNum, final String pNoodleNum, final String pDrinkColumnNum, final String pFoodsColumnNum, final String pNoodleColumnNum)
    {
        if(!isEnable)
            return;
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("51");
        str.append("AVM-01-142    "); //终端软件版本号	14位
        // 终端软件版本号 14位 定长，第一位：0：安卓， 1：X86 第二位：0：横屏，1：竖屏，2：小屏 第三位：‘-’
        // 第四位-第九位：软件版本号，例如1.0.11 其余五位补0
        String version = "0" + String.valueOf(DriverThread.getInstance().softwareType) + "-" + (Configure.version != null ? Configure.version : "");
        if (version.length() > 14) {
            version = version.substring(0, 14);
        } else if (version.length() < 14) {
            int l = 14 - version.length();
            for (int i = 0; i < l; i++) {
                version += "0";
            }
        }
        str.append(version);
        str.append(Configure.getAvmVersion()); //主控板版本号	4
        str.append(Configure.getMacNo()); //售货机编号	8
        str.append(pMacType); //机器类型	2	01饮料机，11食品机，20饮料机一拖N模式
        str.append(pDrinkNum); //饮料机数量	1
        str.append(pFoodsNum); //食品机数量	1
        str.append(pNoodleNum); //泡面柜数量	1
        str.append(pDrinkColumnNum); //饮料机货道数设置	2
        str.append(pFoodsColumnNum); //食品机货道数设置	2
        str.append(pNoodleColumnNum); //泡面柜货道数设置	2
        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        mStrSign = resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("51", resultStr, "normal");
    }

    //52轮询
    synchronized void addMessage52()
    {
        if(!isEnable)
            return;
        if(mStrSign == null)
        {
            return;
        }
        if(System.currentTimeMillis() - mTime52 < mCurrentTime76) //3分钟发一次
        {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("52");
        str.append("521000|1|768|50|8000|2100|");
        if(Configure.context != null) {
            str.append(SimTools.getICCID(Configure.context)).append(":").append(SimTools.getIPAddress(Configure.context)); //ICCID:IP
        }
        str.append("|");
        str.append(DriverThread.getInstance().isStartNormal ? "0" : "1"); //重启1 正常启动0
        str.append(Configure.alipayState == 0 ? "0" : "2"); //支付宝支付开关：0，不使用支付宝支付；1，仅开启声波支付；2，仅开启二维码支付；3两种支付都开启；4反扫;7---2.0
        str.append("|");
        str.append(""); //中奖率

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("52", resultStr, "normal");
        mTime52 = System.currentTimeMillis();
    }

    //61系统运行信息
    synchronized void addMessage61(final String pRunMessage) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData61.equals(pRunMessage)) {
            if (System.currentTimeMillis() - mTime61 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("61");
        str.append(pRunMessage);
        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("61", resultStr, "normal");
        mTime61 = System.currentTimeMillis();
        mData61 = pRunMessage;
    }

    //62料到运行信息
    synchronized void addMessage62(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if(mDataMap62.containsKey(pBox))
        {
            String data = mDataMap62.get(pBox);
            if(data.equals(pData))
            {
                if (System.currentTimeMillis() - mTime62 < 3600000) //60分钟发一次
                {
                    return;
                }
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("62");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("62", resultStr, "normal");
        mTime62 = System.currentTimeMillis();
        mDataMap62.put(pBox, pData);
    }

    //63系统配置信息
    synchronized void addMessage63(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if(mDataMap63.containsKey(pBox))
        {
            String data = mDataMap63.get(pBox);
            if(data.equals(pData))
            {
                if (System.currentTimeMillis() - mTime63 < 3600000) //60分钟发一次
                {
                    return;
                }
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("63");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("63", resultStr, "normal");
        mTime63 = System.currentTimeMillis();
        mDataMap63.put(pBox, pData);
    }

    //64料到配置信息
    synchronized void addMessage64(final int pBox, final String pGoodsData, final String pPriceData) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if (pGoodsData == null || pPriceData == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("64");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pGoodsData);
        str.append(pPriceData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("64", resultStr, "normal");
    }

    //71商品销售信息
    synchronized void addMessage71(final String pBox, final String pRoad, final String pGoodId, final String pPrice, final String pTrace, final String pType, final int pResult, final int pErrorCode, final String pTranCard, final String pTradeTrace, final String pTotalNum, final String pTotalMoney, final String pOrder) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("71");
        str.append(Tools.addLeftZero(pBox, 2)); //货柜
        str.append(Tools.addLeftZero(pRoad, 2)); //货道编号	2
        str.append(Tools.addLeftZero(pGoodId, 2)); //商品序号	2
        str.append(Tools.addLeftZero(pPrice, 6)); //售卖金额	6
        str.append(Tools.addLeftZero(String.valueOf(pTrace), 3)); //序列号	3
        str.append(Tools.addLeftZero(pType, 2)); //支付方式	2
        str.append(String.valueOf(pResult)); //出货情况	1
        str.append(Tools.addLeftZero(String.valueOf(pErrorCode), 2)); //出货失败码
        str.append(pTranCard); //卡号	18
        str.append(Tools.addLeftZero(String.valueOf(pTradeTrace), 6)); //流水号	6
        str.append(Tools.addLeftZero(pTotalNum, 8)); //商品销售总数量	8
        str.append(Tools.addLeftZero(pTotalMoney, 10)); //商品销售的总金额	10
        str.append(Tools.getCurrentTime()); //时间	14
        if(pOrder != null && pOrder.length() > 0)
        {
            str.append(pOrder); //新加入的商户订单号 64位
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("71", resultStr, "normal");
    }

    //72商品销售汇总信息
    synchronized void addMessage72(final String pData) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("72");
        str.append(pData);
        String time = Tools.getCurrentTime();
        str.append(time); //时间1	14
        str.append(time); //时间2	14

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("72", resultStr, "normal");
    }

    //53定位信息
    private void addMessage53()
    {
        if(!isGPSEnable)
        {
            return;
        }
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        String time = Tools.getCurrentTime();
        str.append("53").append(time);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("53", resultStr, "normal");
        mlLastSend53 = System.currentTimeMillis();
    }

    void addMessage81(final String pData)
    {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData81.equals(pData)) {
            if (System.currentTimeMillis() - mTime81 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("81");
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("81", resultStr, "normal");
        mTime81 = System.currentTimeMillis();
        mData81 = pData;
    }

    void addMessage83(final String pData)
    {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData83.equals(pData)) {
            if (System.currentTimeMillis() - mTime83 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("83");
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("83", resultStr, "normal");
        mTime83 = System.currentTimeMillis();
        mData83 = pData;
    }

    @Override
    public void run() {
        super.run();

        while (run) {
            SystemClock.sleep(1000);
            if (!isEnable) {
                run = false;
                return;
            }

            //判断是否该发送53指令了，每半小时发送一次
            if((System.currentTimeMillis() - mlLastSend53) >= 1800000 && mStrSign != null)
            {
                addMessage53();
            }

            String[] messages = GoodsDataBase.getInstance().getMessage();
            if (messages == null || messages.length == 0) {
                continue;
            }
            logger.i("db count:" + messages.length);
            String message = messages[0];
            final String[] con = message.split(";");

            if (con[1] == null) {
                logger.e("message error = " + con[1]);
                GoodsDataBase.getInstance().deleteMessage(con[0]);
                continue;
            }

            if (con.length <= 2) {
                logger.e("message error1 = " + con[1]);
                GoodsDataBase.getInstance().deleteMessage(con[0]);
                continue;
            }
            message = con[1];
            String type = con[2];

//            if (!NetUtils.isNetAvailable()) {
//                logger.i("can not send message : net unvailable");
//                deleteUnusedMessage(type, con[0]);
//                continue;
//            }

            if (type.equals("72")) //72指令需要将最后的14位时间改成当前时间
            {
                message = message.substring(0, message.length() - 14) + Tools.getCurrentTime();
            }
            logger.i("send message : " + message);
            try {
                String respMessage = getServiceInfo(message);
                logger.i("receive message :" + respMessage);
                if (respMessage == null || respMessage.length() < 39) {
                    logger.e("Send " + type + " faild!");
                    deleteUnusedMessage(type, con[0]);
                } else {
                    //type = respMessage.substring(35, 37); // 控制码
                    String resultCode = respMessage.substring(37, 39);
                    if (resultCode.equals("00") || resultCode.equals("04") || resultCode.equals("05") || resultCode.equals("06")) {
                        logger.i("Send " + type + " success!");
                        GoodsDataBase.getInstance().deleteMessage(con[0]);
                        handleResponse(type, respMessage); //处理回复
                        mRetryCount = 0;
                    } else {
                        if(!type.equals("55")) {
                            logger.e("Send " + type + " faild!");
                        }
//                        mRetryCount++;
//                        if(mRetryCount > RETRY_COUNT)
//                        {
//                            mRetryCount = 0;
//                            logger.e("retry 3 times");
//                            GoodsDataBase.getInstance().deleteMessage(con[0]);
//                        }
//                        else {
                            deleteUnusedMessage(type, con[0]);
//                        }
                    }
                }
            } catch (NumberFormatException e) {
                logger.e("NumberFormatException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (SocketTimeoutException e) {
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (UnknownHostException e) {
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (SocketException e) {
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (IOException e) {
                logger.e("IOException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            }
            SystemClock.sleep(5000);
        }
        run = false;
    }

    private void deleteUnusedMessage(final String type, final String id)
    {
        if(type.equals("52") || type.equals("53") || type.equals("54") || type.equals("55"))
        {
            GoodsDataBase.getInstance().deleteMessage(id);
        }
    }

    private String getServiceInfo(String message) throws NumberFormatException,UnknownHostException,SocketException,SocketTimeoutException,IOException{
        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        byte[] buf;
        String respMessage = null;
        try {
            socket = new Socket();
            socket.setSoTimeout(20000);
            SocketAddress socAddress = new InetSocketAddress(Configure.getConfigData(Configure.CONFIG_SERVER_IP), Integer.parseInt(Configure.getConfigData(Configure.CONFIG_SERVER_PORT)));
            socket.connect(socAddress, 10000);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            out.write(message.getBytes());
            out.flush();
            buf = new byte[4];
            in.read(buf);
            String sString = new String(buf);
            if("".equals(sString.trim())) return message.substring(0, 37)+"88";
            buf = new byte[Integer.valueOf(sString.trim())];
            in.read(buf);
            respMessage = sString + new String(buf);
        } finally{
            if(socket != null) socket.close();
            if(in != null) in.close();
            if(out != null) out.close();
        }
        return respMessage;
    }

    private void handleResponse(final String pType, final String pMessage)
    {
        if(pType.equals("51")) //51签到
        {
            handle51(pMessage);
        }
        else if(pType.equals("53")) //53位置信息
        {
            handle53(pMessage);
        }
        else if(pType.equals("52")) //52轮询
        {
            handle52(pMessage);
        }
    }

    private void handle51(final String pMessage)
    {
        String serverTime = pMessage.substring(39, 53);
        logger.i("Sign success, serverTime = " + serverTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
        try {
            long serverTimeLong = sdf.parse(serverTime).getTime();
            if (Math.abs((new Date()).getTime() - serverTimeLong) > 10000) {
                SystemTools.setSystemTime(serverTime.substring(0, 8)+"."+serverTime.substring(8));
            }
            DriverThread.getInstance().setAvmTime(serverTime);
            //发送53指令，位置信息查询
            addMessage53();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void handle53(final String pMessage)
    {
        if(pMessage.length() <= 39) //不带经纬度信息,直接忽略
        {
            logger.i("53 no GPS message!");
            return;
        }
        //纬度 9
        String strLatitude = pMessage.substring(39, 48);
        double dLatitude = Double.parseDouble(strLatitude.substring(0, 3) + "." + strLatitude.substring(3)); //转换成double型
        //经度  9
        String strLongitude = pMessage.substring(48, 57);
        double dLongitude = Double.parseDouble(strLongitude.substring(0, 3) + "." + strLongitude.substring(3)); //转换成double型
        //报警偏差范围 5
        String strRange = pMessage.substring(57, 62);
        int iRange = Integer.parseInt(strRange);
        //流水号 3
        String strNo = pMessage.substring(62, 65);
        //发送54指令，定位信息
        StringBuffer str = new StringBuffer();
        String time = Tools.getCurrentTime();
        str.append(getMsgHeader());
        str.append("54");
        str.append(Tools.addLeftZero(String.valueOf(miLocationType), 3)); //故障代码
        if(mdLongitude < 0.0001 && mdLatitude < 0.0001)
        {
            //没有获取到位置坐标
            str.append("000000000");
            str.append("000000000");
            //偏差距离 5
            str.append("00000");
            //报警状态 1
            str.append("0");
        }
        else
        {
            //纬度 9
            strLatitude = String.valueOf(mdLatitude);
            logger.i("strLatitude:"+strLatitude);
            int pos = strLatitude.indexOf(".");
            if(pos >= 0)
            {
                strLatitude = Tools.addLeftZero(strLatitude.substring(0, pos), 3) + strLatitude.substring(pos + 1);
            }
            for(int i1 = 0;i1 < 9 - strLatitude.length();i1++)
            {
                strLatitude += "0";
            }
            str.append(strLatitude);
            //经度  9
            strLongitude = String.valueOf(mdLongitude);
            logger.i("strLongitude:"+strLongitude);
            pos = strLongitude.indexOf(".");
            if(pos >= 0)
            {
                strLongitude = Tools.addLeftZero(strLongitude.substring(0, pos), 3) + strLongitude.substring(pos + 1);
            }
            for(int i2 = 0;i2 < 9 - strLongitude.length();i2++)
            {
                strLongitude += "0";
            }
            str.append(strLongitude);
            //偏差距离 5
            int distance = (int)Tools.GetDistance(dLongitude, dLatitude, mdLongitude, mdLatitude);
//								int minus = Math.abs(iRange - distance);
            String strMinus = String.valueOf(distance);
            if(strMinus.length() > 5)
            {
                strMinus = strMinus.substring(0, 5);
            }
            str.append(Tools.addLeftZero(strMinus, 5));
            //报警状态 1
            str.append(iRange >= distance ? "0" : "1");
        }
        //流水号
        str.append(strNo);
        //定位时间
        str.append(time);
        String sendMessage = str.toString();
        sendMessage = Tools.addLeftZero(String.valueOf(sendMessage.length()), 4) + sendMessage;
        logger.i("insert db: " + sendMessage);

        insertDataToDB("54", sendMessage, "normal");
    }

    private void handle52(final String pMessage)
    {
        String resultCode = pMessage.substring(37, 39);
        if(resultCode.equals("00")) {
            mCurrentTime76 = DRIVER_TIME_76_NORMAL;
            return;
        }
        else if(resultCode.equals("04"))
        {
            logger.i("52 04:" + pMessage);
            //设置料道商品信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count = (pMessage.charAt(56) - '0') & 0xFF;
            logger.i("52 04 count:" + count);
            if(count < 1 || pMessage.length() < count * 10 + 57 + 2 /*柜号*/ + 2 /*保留位*/)
            {
                logger.e("52 04 error");
                return;
            }
            int pos = 0;
            byte box = 0x00;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(57)).append(pMessage.charAt(58));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 04 box: "+Tools.bytesToHexString(box));
            pos = 59;
            for(int i1 = 0;i1 < count;i1++)
            {
                String dataByteArray = pMessage.substring(pos, pos + 10);
                StringBuffer dataStr = new StringBuffer();
                byte[] soldSendData = new byte[10];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x04; //设置料道信息0x04
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
                soldSendData[3] = Byte.parseByte(dataStr.toString()); //货道号
                //商品ID1字节
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(2)).append(dataByteArray.charAt(3));
                soldSendData[4] = Integer.valueOf(dataStr.toString(), 16).byteValue(); //商品ID
                //价格2字节，角为单位
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(4)).append(dataByteArray.charAt(5)).append(dataByteArray.charAt(6)).append(dataByteArray.charAt(7));
                int price = Integer.parseInt(dataStr.toString());
                soldSendData[5] = (byte)((price >> 8) & 0xFF);
                soldSendData[6] = (byte)(price & 0xFF); //价格
                //是否参加抽奖，1字节
                if(dataByteArray.charAt(8) == '1')
                {
                    soldSendData[7] = 0x01;
                }
                else
                {
                    soldSendData[7] = 0x00;
                }
                //预留，1字节
                soldSendData[8] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[9] = sumByte;
                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
                logger.i("76 04: "+Tools.bytesToHexString(soldSendData));
                pos += 10;
            }
            //发送55指令到服务器
            send55(pMessage);
        }
        else if(resultCode.equals("05"))
        {
            logger.i("52 05:" + pMessage);
            //设置料道加货信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count = (pMessage.charAt(56) - '0') & 0xFF;
            logger.i("52 05 count:" + count);
            if(count < 1 || pMessage.length() < count * 4 + 57 + 2 /*柜号*/ + 2 /*保留位*/)
            {
                logger.e("52 05 error");
                return;
            }
            int pos = 0;
            byte box = 0x00;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(57)).append(pMessage.charAt(58));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 05 box: "+Tools.bytesToHexString(box));
            pos = 59;
            for(int i1 = 0;i1 < count;i1++)
            {
                String dataByteArray = pMessage.substring(pos, pos + 4);
                StringBuffer dataStr = new StringBuffer();
                byte[] soldSendData = new byte[8];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x05; //设置料道加货信息0x05
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
                soldSendData[3] = Byte.parseByte(dataStr.toString()); //货道号
                //加货数量1字节
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(2)).append(dataByteArray.charAt(3));
                soldSendData[4] = Integer.valueOf(dataStr.toString(), 16).byteValue(); //加货数量
                //预留，2字节
                soldSendData[5] = 0x00;
                soldSendData[6] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[7] = sumByte;
                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
                logger.i("76 05: "+Tools.bytesToHexString(soldSendData));
                pos += 4;
            }
            //发送55指令到服务器
            send55(pMessage);
        }
        else if(resultCode.equals("06"))
        {
            logger.i("52 06:" + pMessage);
            //设置系统状态信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            if(pMessage.length() < 57)
            {
                logger.e("52 06 error");
                return;
            }
            String dataByteArray = pMessage.substring(56);
            StringBuffer dataStr = new StringBuffer();
            byte[] soldSendData = new byte[18];
            soldSendData[0] = 0x76; //0x76
            soldSendData[1] = 0x06; //设置系统状态信息0x06
            //柜号1字节
            dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
            soldSendData[2] = Byte.parseByte(dataStr.toString()); //柜号
            //预留1字节
            soldSendData[3] = 0x00;
            //照明状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(10)).append(dataByteArray.charAt(11));
            soldSendData[4] = Byte.parseByte(dataStr.toString()); //照明状态
            //日光灯时间4字节BCD码
            byte[] bcd = Tools.bcdStringToBytes(dataByteArray.substring(12, 16));
            soldSendData[5] = bcd[0];
            soldSendData[6] = bcd[1]; //开灯时间
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(16, 20));
            soldSendData[7] = bcd[0];
            soldSendData[8] = bcd[1]; //停止时间
            //左室状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(20)).append(dataByteArray.charAt(21));
            soldSendData[9] = Byte.parseByte(dataStr.toString()); //左室状态
            //右室状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(22)).append(dataByteArray.charAt(23));
            soldSendData[10] = Byte.parseByte(dataStr.toString()); //右室状态
            //节能时间4字节BCD码
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(24, 28));
            soldSendData[11] = bcd[0];
            soldSendData[12] = bcd[1]; //节能开始时间
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(28, 32));
            soldSendData[13] = bcd[0];
            soldSendData[14] = bcd[1]; //节能停止时间
            //制冷温度1字节
            char c1 = dataByteArray.charAt(32); //正负号
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(33)).append(dataByteArray.charAt(34));
            int temp = Integer.parseInt(dataStr.toString()) & 0xFF;
            if(c1 == '-')
            {
                temp = temp | 0x80; //最高位置1
            }
            soldSendData[15] = (byte)temp;
            //加热温度1字节
            c1 = dataByteArray.charAt(35); //正负号
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(36)).append(dataByteArray.charAt(37));
            temp = Integer.parseInt(dataStr.toString()) & 0xFF;
            if(c1 == '-')
            {
                temp = temp | 0x80; //最高位置1
            }
            soldSendData[16] = (byte)temp;
            //校验和
            byte sumByte = 0x00;
            for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                sumByte += soldSendData[i2];
            }
            soldSendData[17] = sumByte;
            DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
            logger.i("76 06: "+Tools.bytesToHexString(soldSendData));
            //发送55指令到服务器
            send55(pMessage);
        }
    }

    //发送55指令
    private void send55(final String pMessage)
    {
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("55"); //控制码
        str.append(pMessage.substring(37, 39)); //响应码
        str.append("00"); //回复确认
        str.append(pMessage.substring(39, 56)); //时间及流水号,原样返回
        String sendMessage = str.toString();
        sendMessage = Tools.addLeftZero(String.valueOf(sendMessage.length()), 4) + sendMessage;
        logger.i("insert db: " + sendMessage);

        insertDataToDB("55", sendMessage, "normal");
    }

    /**
     * 设置经纬度
     * @param pLongitude 经度
     * @param pLatitude 纬度
     * @param pType 定位类型
     */
    public static void setLocationInfo(final double pLongitude, final double pLatitude, final int pType)
    {
        mdLongitude = pLongitude; //经度
        mdLatitude = pLatitude; //纬度
        miLocationType = pType; //定位类型
        isGPSEnable = true;
    }

//    public interface GPSHandler {
//        void init(final Context context);
//    }
//
//    public static void setGPSHandler(final GPSHandler handler)
//    {
//        if(handler != null)
//        {
//            mGPSHandler = handler;
//            isGPSEnable = true;
//        }
//    }
//
//    public static void removeGPSHandler()
//    {
//        mGPSHandler = null;
//        isGPSEnable = false;
//    }
}
